﻿@page "/"
@inject HttpClient Http

    <style>
        .site-layout-background {
            background: #fff;
        }
    </style>

<Tabs Type="@TabType.EditableCard" TabPosition="TabPosition.Top" Style="height: 100%;" @bind-ActiveKey="activeKey" OnAddClick="AddContent" OnClose="OnTabClose">
    <TabPane Tab="内容分类" Key="list" Style="height: 100%;" Closable="false">
        <Layout Class="site-layout-background">
            <Sider Width="200" Class="site-layout-background">
                <ContextMenuPanel OnContextMenu="OnContextMenuFunction" OnClick="OnMenuTreeClickFunction">
                    <Tree @ref="menuTree" TItem="DiaryTreeNode<Model.Category>" DataSource="@_trees" TitleExpression="x => x.DataItem.Entity.Name" ChildrenExpression="x => x.DataItem.Nodes" OnSelect="OnTreeNodeSelect" ShowLine="true">
                    </Tree>
                    <Menu Style="@menuStyle">
                        <MenuItem OnClick="CreateNode">
                            @menu_create_text
                        </MenuItem>
                        <MenuItem OnClick="ModifyNode">
                            修改节点
                        </MenuItem>
                        <MenuItem OnClick="DeleteNode">
                            删除节点
                        </MenuItem>
                    </Menu>
                    <CategoryEdit @ref="categoryEditor" Value="@curCategory" OnSave="@SaveCategory"></CategoryEdit>
                </ContextMenuPanel>
            </Sider>

            <Layout Style="padding: 0px; height: 100%;" Class="site-layout-background">
                @if (_contents.Count == 0)
                {
                    <p>暂无内容</p>
                }
                else
                {
                    //transfer_rule_data();
                    <Table TItem="Model.Content" DataSource="@_contents" Total="_total" @bind-PageIndex="_pageIndex" @bind-PageSize="_pageSize">
                        <Column @bind-Field="@context.Id" />
                        <Column @bind-Field="@context.Title" Sortable />
                        <Column @bind-Field="@context.RealTime" Sortable />
                        <ActionColumn>
                            <Space>
                                <SpaceItem><Button Danger OnClick="() => Edit(context)">编辑</Button></SpaceItem>
                                <SpaceItem><Button Danger OnClick="() => Delete(context)">删除</Button></SpaceItem>
                            </Space>
                        </ActionColumn>
                    </Table>
                }
            </Layout>
        </Layout>
    </TabPane>
    @foreach (var pane in panes)
    {
        <TabPane Key="@pane.Key" Tab="@pane.Title" Closable="@pane.Closable">
            <iframe style="width:100%; min-height:850px;" frameborder="0" scrolling="auto" id="iframe" src="@pane.Url" />
        </TabPane>
    }
</Tabs>



@code
{
    #region 多标签
    string activeKey = "";
    public record Pane(string Title, string Url, string Key, bool Closable = true);
    List<Pane> panes = new List<Pane>();

    void OnTabClose(string key)
    {
        foreach (Pane p in panes)
        {
            if (p.Key == key)
            {
                panes.Remove(p);
                break;
            }
        }

    }
    #endregion

    #region 内容列表
    List<Model.Content> _contents = new List<Model.Content>();

    int _pageIndex = 1;
    int _pageSize = 5;
    int _total = 0;

    private void AddContent()
    {
        if (menuTree.SelectedNode == null) return;

        string url = string.Format("/ContentEdit?pid={0}", menuTree.SelectedNode.DataItem.Entity.Id);
        string key = Guid.NewGuid().ToString();
        panes.Add(new Pane($"新建内容:" + menuTree.SelectedNode.DataItem.Entity.Name, url, key, true));
        activeKey = key;
    }

    private void Edit(Model.Content item)
    {
        foreach (Pane p in panes)
        {
            if (p.Key == item.Id.ToString())
            {
                activeKey = item.Id.ToString();
                return;
            }
        }

        var key = item.Id.ToString();
        activeKey = key;
        string url = "/ContentEdit?id=" + item.Id;

        panes.Add(new Pane($"内容管理:{item.Title}", url, key, true));
    }

    private async void Delete(Model.Content item)
    {
        string pms = string.Format("id={0}", item.Id);
        string url = Tools.get_api_url("content", "delete", pms);
        string ret = await Http.GetStringAsync(url);
        if (ret == "ok")
        {
            update_contents();
        }
    }

    async void update_contents()
    {
        if (menuTree.SelectedNode == null) return;

        _contents.Clear();
        string pms = string.Format("cid={0}", menuTree.SelectedNode.DataItem.Entity.Id);
        string url = Tools.get_api_url("content", "get_by_category", pms);
        string content_data = await Http.GetStringAsync(url);
        _contents = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.Content>>(content_data);
        _total = _contents.Count;
        StateHasChanged();
    }
    #endregion


    public class DiaryTreeNode<T>
    {
        public T Entity;
        public List<DiaryTreeNode<T>> Nodes = new List<DiaryTreeNode<T>>();
    }

    List<DiaryTreeNode<Model.Category>> _trees = new List<DiaryTreeNode<Model.Category>>();

    DiaryTreeNode<Model.Category> find_by_id(DiaryTreeNode<Model.Category> tnParent, int findId)
    {
        List<DiaryTreeNode<Model.Category>> tnc = (tnParent == null) ? _trees : tnParent.Nodes;

        foreach (DiaryTreeNode<Model.Category> node in tnc)
        {
            Model.Category model = node.Entity as Model.Category;
            if (model.Id == findId) return node;

            if (node.Nodes.Count > 0)
            {
                DiaryTreeNode<Model.Category> tn = find_by_id(node, findId);
                if (tn != null) return tn;
            }
        }
        return null;
    }

    protected override async Task OnInitializedAsync()
    {
        UpdateMenuTree();
    }

    async Task UpdateMenuTree()
    {
        _trees.Clear();
        string url = Tools.get_api_url("category", "get_all");
        string category_data = await Http.GetStringAsync(url);
        List<Model.Category> categories = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.Category>>(category_data);
        //List<Model.Category> categories = Model.Category.get_test();
        categories = Model.Category.Sort(categories);
        foreach (Model.Category category in categories)
        {
            DiaryTreeNode<Model.Category> tn_parent = find_by_id(null, category.ParentId);
            List<DiaryTreeNode<Model.Category>> tnc = (tn_parent == null) ? _trees : tn_parent.Nodes;
            DiaryTreeNode<Model.Category> tn = new DiaryTreeNode<Model.Category>();
            tn.Entity = category;
            tnc.Add(tn);
        }
        StateHasChanged();
    }

    async void OnTreeNodeSelect(TreeEventArgs<DiaryTreeNode<Model.Category>> args)
    {
        if (args.Node == null) return;

        _contents.Clear();
        string pms = string.Format("cid={0}", args.Node.DataItem.Entity.Id);
        string url = Tools.get_api_url("content", "get_by_category", pms);
        string content_data = await Http.GetStringAsync(url);
        _contents = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Model.Content>>(content_data);
        _total = _contents.Count;
        StateHasChanged();
    }


    string menuStyle = "display:none;";

    void CreateNode(MouseEventArgs args)
    {
        menuStyle = "display:none;";

        curCategory = new Model.Category();
        curCategory.Id = -1;
        curCategory.ParentId = menuTree.SelectedNode.DataItem.Entity.Id;
        categoryEditor.toggle();
    }

    void ModifyNode(MouseEventArgs args)
    {
        menuStyle = "display:none;";
        curCategory = menuTree.SelectedNode.DataItem.Entity;
        categoryEditor.toggle();
    }

    async void DeleteNode(MouseEventArgs args)
    {
        menuStyle = "display:none;";
        string pms = string.Format("id={0}", menuTree.SelectedNode.DataItem.Entity.Id);
        string url = Tools.get_api_url("category", "delete", pms);
        string category_data = await Http.GetStringAsync(url);
        UpdateMenuTree();
    }

    CategoryEdit categoryEditor;
    Model.Category curCategory = new Model.Category();
    void SaveCategory()
    {
        string function = curCategory.Id > 0 ? "update" : "insert";
        string post_url = Tools.get_api_url("category", function);
        string post_data = Newtonsoft.Json.JsonConvert.SerializeObject(curCategory);

        var httpRequestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Post,
            RequestUri = new Uri(post_url),
            Content = new StringContent(post_data, System.Text.Encoding.UTF8, "application/json")
        };
        var httpReponseMessage = Http.SendAsync(httpRequestMessage);
        UpdateMenuTree();
    }


    void OnMenuTreeClickFunction(MouseEventArgs args)
    {
        menuStyle = "display:none;";
    }

    string menu_create_text = "创建子节点";
    Tree<DiaryTreeNode<Model.Category>> menuTree = null;
    void OnContextMenuFunction(MouseEventArgs args)
    {
        if (menuTree.SelectedNode == null)
        {
            menu_create_text = "创建根节点";
        }
        else
        {
            menu_create_text = "创建子节点";
        }
        menuStyle = string.Format("position:fixed; left:{0}px; top:{1}px; width:200px; z-index:999", args.ClientX, args.ClientY);
    }


}
